import React from 'react';
import { ModalForm } from '@ant-design/pro-form';
import { handleUpdate } from '@/utils/actions';
import { ActionType } from '@ant-design/pro-table';

type MegaUpdateFormProps = {
  title: string,
  modalVisible: boolean,
  handleModalVisible: (visible: boolean) => void,
  children: React.ReactNode,
  actionRef?: React.MutableRefObject<ActionType | undefined>,
  currentEntity?: BaseTableEntity
  getEntityAction: any,
  updateEntityAction: any,
  transform?: (value: any) => any;
  onSuccess?: () => void;
}

export default (props: MegaUpdateFormProps) => {
  const {
    title,
    modalVisible,
    handleModalVisible,
    actionRef,
    children,
    getEntityAction,
    updateEntityAction,
    currentEntity,
    transform,
    onSuccess
  } = props;
  return (
    <ModalForm title={title}
      visible={modalVisible}
      onVisibleChange={handleModalVisible}
      modalProps={{
        destroyOnClose: true,
      }}
      request={async () => {
        return getEntityAction(currentEntity?.id);
      }}
      onFinish={async (value) => {
        const newValue = transform ? transform(value) : value;
        const success = await handleUpdate(currentEntity?.id, newValue, updateEntityAction);
        if (success) {
          handleModalVisible(false);
          if (actionRef?.current) {
            await actionRef.current.reload();
          }
          if (onSuccess) onSuccess()
        }
      }}>
      {children}
    </ModalForm>
  );
}
